package q13_romanToInt;

public class Solution {
    public static void main(String[] args) {
        System.out.println(romanToInt("LVIII"));
    }

    public static int romanToInt(String s){
        // I， V， X， L，C，D 和 M
        char[] chars = s.toCharArray();
        int res = 0;
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == 'I') {
                res += 1;
            } else if (chars[i] == 'V') {
                try{if(chars[i - 1] == 'I'){
                    res -= 1;
                    i--;
                }}catch (Exception e) {
                    // e.printStackTrace();
                }
                res += 5;
            }else if (chars[i] == 'X') {
                try{if(chars[i - 1] == 'I'){
                    res -= 1;
                    i--;
                }}catch (Exception e) {
                    // e.printStackTrace();
                }
                res += 10;
            }else if (chars[i] == 'L') {
                try{if(chars[i - 1] == 'X'){
                    res -= 10;
                    i--;
                }}catch (Exception e) {
                    // e.printStackTrace();
                }
                res += 50;
            }else if (chars[i] == 'C') {
                try{if(chars[i - 1] == 'X'){
                    res -= 10;
                    i--;
                }}catch (Exception e) {
                    // e.printStackTrace();
                }
                res += 100;
            }else if (chars[i] == 'D') {
                try{if(chars[i - 1] == 'C'){
                    res -= 100;
                    i--;
                }}catch (Exception e) {
                    // e.printStackTrace();
                }
                res += 500;
            }else if (chars[i] == 'M') {
                try{if(chars[i - 1] == 'C'){
                    res -= 100;
                    i--;
                }}catch (Exception e) {
                    // e.printStackTrace();
                }
                res += 1000;
            }
        }

        return res;
    }
}
